package com.czk.utlls;

import com.alibaba.fastjson.JSONObject;
import com.czk.pojo.AccessToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/2 17:14
 */
@Component
public class TokenUtil {
    @Value("${token.url:http://www.baidu.com}")
    private String url;
    @Value("${appId:czk}")
    private String appId;
    @Value("${secret:czk}")
    private String secret;

    /**
     * 获取token
     *
     * @return
     */
    public AccessToken getToken() {
        // 替换
        url = url.replace("APPID", appId).replace("APPSECRET", secret);
        try {
            URL urlObject = new URL(url);
            URLConnection urlConnection = urlObject.openConnection();
            // 拿到输入流
            InputStream inputStream = urlConnection.getInputStream();
            byte[] b = new byte[1024];
            int length = 0;
            StringBuilder builder = new StringBuilder();
            while ((length = inputStream.read(b)) != -1) {
                builder.append(new String(b, 0, length));
            }
            String str = builder.toString();
            JSONObject jsonObject = JSONObject.parseObject(str);
            AccessToken accessToken = new AccessToken(jsonObject.getString("access_token"), jsonObject.getString("expires_in"));
            return accessToken;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
